<!--
  智慧社区管理系统 - 停车场管理 (静态展示页面)
  @author Wu.Liang
  @date 2024-01-01
-->
<template>
    <div class="lot-container">
        <!-- 页面标题 -->
        <el-card class="title-card">
            <div class="page-header">
                <h2>🏢 停车场管理</h2>
                <p class="page-description">管理社区内所有停车场信息，包括停车场配置、收费标准、容量管理等功能</p>
            </div>
        </el-card>

        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" inline>
                <el-form-item label="停车场名称">
                    <el-input v-model="searchForm.lotName" placeholder="请输入停车场名称" clearable />
                </el-form-item>
                <el-form-item label="停车场类型">
                    <el-select v-model="searchForm.lotType" placeholder="请选择停车场类型" clearable>
                        <el-option label="地下停车场" :value="1" />
                        <el-option label="地面停车场" :value="2" />
                        <el-option label="立体车库" :value="3" />
                        <el-option label="访客停车场" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                        <el-option label="正常" :value="1" />
                        <el-option label="维护" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 统计信息卡片 -->
        <el-row :gutter="20" class="stats-row">
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon success">
                            <el-icon><OfficeBuilding /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.total }}</div>
                            <div class="stats-label">总停车场数</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon primary">
                            <el-icon><Parking /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.totalSpaces }}</div>
                            <div class="stats-label">总车位数</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon warning">
                            <el-icon><CarFilled /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.occupiedSpaces }}</div>
                            <div class="stats-label">已占用车位</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card">
                    <div class="stats-content">
                        <div class="stats-icon info">
                            <el-icon><TrendCharts /></el-icon>
                        </div>
                        <div class="stats-info">
                            <div class="stats-number">{{ stats.occupancyRate }}%</div>
                            <div class="stats-label">使用率</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 操作区域 -->
        <el-card class="operation-card">
            <el-button type="primary" @click="handleAdd">添加停车场</el-button>
            <el-button type="success" @click="handleBatchAdd">批量添加</el-button>
            <el-button type="warning" @click="handleRefresh">刷新</el-button>
            <el-button type="info" @click="handleExport">导出数据</el-button>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="table-card">
            <el-table :data="filteredTableData" border v-loading="loading" stripe>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="lotName" label="停车场名称" width="150" />
                <el-table-column prop="lotTypeName" label="停车场类型" width="120" />
                <el-table-column prop="location" label="位置描述" width="200" />
                <el-table-column prop="totalSpaces" label="总车位数" width="100" />
                <el-table-column prop="availableSpaces" label="空闲车位数" width="100" />
                <el-table-column prop="occupiedSpaces" label="占用车位数" width="100" />
                <el-table-column prop="hourlyRate" label="小时费率" width="100">
                    <template #default="{ row }">
                        ¥{{ row.hourlyRate }}/小时
                    </template>
                </el-table-column>
                <el-table-column prop="statusName" label="状态" width="80">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">{{ row.statusName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" />
                <el-table-column label="操作" width="250" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button type="success" size="small" @click="handleViewSpaces(row)">查看车位</el-button>
                        <el-button type="warning" size="small" @click="handleViewDetails(row)">详情</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="600px"
            @close="handleDialogClose"
        >
            <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="停车场名称" prop="lotName">
                            <el-input v-model="form.lotName" placeholder="请输入停车场名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="停车场类型" prop="lotType">
                            <el-select v-model="form.lotType" placeholder="请选择停车场类型" style="width: 100%">
                                <el-option label="地下停车场" :value="1" />
                                <el-option label="地面停车场" :value="2" />
                                <el-option label="立体车库" :value="3" />
                                <el-option label="访客停车场" :value="4" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="总车位数" prop="totalSpaces">
                            <el-input-number v-model="form.totalSpaces" :min="1" :max="1000" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="小时费率" prop="hourlyRate">
                            <el-input-number v-model="form.hourlyRate" :min="0" :precision="2" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="位置描述" prop="location">
                    <el-input v-model="form.location" placeholder="请输入位置描述" />
                </el-form-item>
                <el-form-item label="开放时间" prop="openTime">
                    <el-time-picker
                        v-model="form.openTime"
                        placeholder="开始时间"
                        format="HH:mm"
                        style="width: 45%"
                    />
                    <span style="margin: 0 10px">至</span>
                    <el-time-picker
                        v-model="form.closeTime"
                        placeholder="结束时间"
                        format="HH:mm"
                        style="width: 45%"
                    />
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                                <el-option label="正常" :value="1" />
                                <el-option label="维护" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否24小时" prop="is24Hours">
                            <el-switch v-model="form.is24Hours" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
            </template>
        </el-dialog>

        <!-- 停车场详情对话框 -->
        <el-dialog
            v-model="detailsDialogVisible"
            title="停车场详情"
            width="800px"
        >
            <el-descriptions :column="2" border>
                <el-descriptions-item label="停车场名称">{{ selectedLot.lotName }}</el-descriptions-item>
                <el-descriptions-item label="停车场类型">{{ selectedLot.lotTypeName }}</el-descriptions-item>
                <el-descriptions-item label="位置描述">{{ selectedLot.location }}</el-descriptions-item>
                <el-descriptions-item label="总车位数">{{ selectedLot.totalSpaces }}</el-descriptions-item>
                <el-descriptions-item label="空闲车位数">{{ selectedLot.availableSpaces }}</el-descriptions-item>
                <el-descriptions-item label="占用车位数">{{ selectedLot.occupiedSpaces }}</el-descriptions-item>
                <el-descriptions-item label="小时费率">¥{{ selectedLot.hourlyRate }}/小时</el-descriptions-item>
                <el-descriptions-item label="开放时间">{{ selectedLot.openTime }} - {{ selectedLot.closeTime }}</el-descriptions-item>
                <el-descriptions-item label="是否24小时">{{ selectedLot.is24Hours ? '是' : '否' }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                    <el-tag :type="getStatusType(selectedLot.status)">{{ selectedLot.statusName }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ selectedLot.createTime }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ selectedLot.remark || '无' }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 查看车位对话框 -->
        <el-dialog
            v-model="spacesDialogVisible"
            title="停车场车位详情"
            width="1000px"
        >
            <el-table :data="lotSpaces" border stripe>
                <el-table-column prop="spaceNo" label="车位号" width="100" />
                <el-table-column prop="spaceTypeName" label="车位类型" width="100" />
                <el-table-column prop="statusName" label="状态" width="80">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">{{ row.statusName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="licensePlate" label="车牌号" width="120" />
                <el-table-column prop="ownerName" label="车主姓名" width="100" />
                <el-table-column prop="enterTime" label="进场时间" width="180" />
                <el-table-column prop="duration" label="停车时长" width="100" />
                <el-table-column prop="fee" label="费用" width="100">
                    <template #default="{ row }">
                        ¥{{ row.fee || '0.00' }}
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { OfficeBuilding, TrendCharts } from '@element-plus/icons-vue'
import { showSuccess, showError } from '@/utils/message'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailsDialogVisible = ref(false)
const spacesDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()

// 静态数据 - 停车场列表
const tableData = ref([
    {
        id: 1,
        lotName: 'A区地下停车场',
        lotType: 1,
        lotTypeName: '地下停车场',
        location: '社区A区地下负一层',
        totalSpaces: 50,
        availableSpaces: 30,
        occupiedSpaces: 20,
        hourlyRate: 5.00,
        openTime: '00:00',
        closeTime: '23:59',
        is24Hours: true,
        status: 1,
        statusName: '正常',
        createTime: '2024-01-15 10:30:00',
        remark: '主要停车场，24小时开放'
    },
    {
        id: 2,
        lotName: 'B区地面停车场',
        lotType: 2,
        lotTypeName: '地面停车场',
        location: '社区B区地面',
        totalSpaces: 30,
        availableSpaces: 15,
        occupiedSpaces: 15,
        hourlyRate: 3.00,
        openTime: '06:00',
        closeTime: '22:00',
        is24Hours: false,
        status: 1,
        statusName: '正常',
        createTime: '2024-01-15 11:00:00',
        remark: '地面停车场，夜间关闭'
    },
    {
        id: 3,
        lotName: 'C区立体车库',
        lotType: 3,
        lotTypeName: '立体车库',
        location: '社区C区立体车库',
        totalSpaces: 40,
        availableSpaces: 20,
        occupiedSpaces: 20,
        hourlyRate: 6.00,
        openTime: '00:00',
        closeTime: '23:59',
        is24Hours: true,
        status: 1,
        statusName: '正常',
        createTime: '2024-01-15 11:30:00',
        remark: '立体车库，自动化管理'
    },
    {
        id: 4,
        lotName: '访客专用停车场',
        lotType: 4,
        lotTypeName: '访客停车场',
        location: '社区入口访客区',
        totalSpaces: 20,
        availableSpaces: 10,
        occupiedSpaces: 10,
        hourlyRate: 8.00,
        openTime: '00:00',
        closeTime: '23:59',
        is24Hours: true,
        status: 1,
        statusName: '正常',
        createTime: '2024-01-15 12:00:00',
        remark: '访客专用，临时停车'
    },
    {
        id: 5,
        lotName: 'D区地下停车场',
        lotType: 1,
        lotTypeName: '地下停车场',
        location: '社区D区地下负二层',
        totalSpaces: 60,
        availableSpaces: 45,
        occupiedSpaces: 15,
        hourlyRate: 4.50,
        openTime: '00:00',
        closeTime: '23:59',
        is24Hours: true,
        status: 0,
        statusName: '维护',
        createTime: '2024-01-15 12:30:00',
        remark: '设备维护中，暂停使用'
    }
])

// 停车场车位详情
const lotSpaces = ref<any[]>([])

// 选中的停车场详情
const selectedLot = ref<any>({})

// 统计信息
const stats = computed(() => {
    const total = tableData.value.length
    const totalSpaces = tableData.value.reduce((sum, item) => sum + item.totalSpaces, 0)
    const occupiedSpaces = tableData.value.reduce((sum, item) => sum + item.occupiedSpaces, 0)
    const occupancyRate = totalSpaces > 0 ? Math.round((occupiedSpaces / totalSpaces) * 100) : 0
    
    return { total, totalSpaces, occupiedSpaces, occupancyRate }
})

// 分页
const pagination = reactive({
    current: 1,
    size: 10,
    total: 0
})

// 搜索表单
const searchForm = reactive({
    lotName: '',
    lotType: null,
    status: null
})

// 表单数据
const form = reactive({
    id: null,
    lotName: '',
    lotType: 1,
    location: '',
    totalSpaces: 50,
    hourlyRate: 5.00,
    openTime: '',
    closeTime: '',
    is24Hours: true,
    status: 1,
    remark: ''
})

// 表单验证规则
const rules: FormRules = {
    lotName: [{ required: true, message: '请输入停车场名称', trigger: 'blur' }],
    lotType: [{ required: true, message: '请选择停车场类型', trigger: 'change' }],
    location: [{ required: true, message: '请输入位置描述', trigger: 'blur' }],
    totalSpaces: [{ required: true, message: '请输入总车位数', trigger: 'blur' }],
    hourlyRate: [{ required: true, message: '请输入小时费率', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 过滤后的表格数据
const filteredTableData = computed(() => {
    let filtered = [...tableData.value]
    
    if (searchForm.lotName) {
        filtered = filtered.filter(item => item.lotName.includes(searchForm.lotName))
    }
    
    if (searchForm.lotType !== null) {
        filtered = filtered.filter(item => item.lotType === searchForm.lotType)
    }
    
    if (searchForm.status !== null) {
        filtered = filtered.filter(item => item.status === searchForm.status)
    }
    
    // 更新分页总数
    pagination.total = filtered.length
    
    // 分页处理
    const start = (pagination.current - 1) * pagination.size
    const end = start + pagination.size
    return filtered.slice(start, end)
})

// 获取状态类型
const getStatusType = (status: number) => {
    switch (status) {
        case 1: return 'success'
        case 0: return 'danger'
        default: return 'info'
    }
}

// 搜索
const handleSearch = () => {
    pagination.current = 1
    showSuccess('搜索完成')
}

// 重置
const handleReset = () => {
    Object.assign(searchForm, {
        lotName: '',
        lotType: null,
        status: null
    })
    pagination.current = 1
    showSuccess('重置完成')
}

// 刷新
const handleRefresh = () => {
    showSuccess('数据已刷新')
}

// 导出数据
const handleExport = () => {
    showSuccess('数据导出功能演示 - 实际开发中会生成Excel文件')
}

// 批量添加
const handleBatchAdd = () => {
    showSuccess('批量添加功能演示 - 实际开发中会批量创建停车场')
}

// 添加
const handleAdd = () => {
    dialogTitle.value = '添加停车场'
    Object.assign(form, {
        id: null,
        lotName: '',
        lotType: 1,
        location: '',
        totalSpaces: 50,
        hourlyRate: 5.00,
        openTime: '',
        closeTime: '',
        is24Hours: true,
        status: 1,
        remark: ''
    })
    dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑停车场'
    Object.assign(form, row)
    dialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm('确定要删除该停车场吗？', '提示', {
            type: 'warning'
        })
        
        // 模拟删除操作
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index > -1) {
            tableData.value.splice(index, 1)
            showSuccess('删除成功')
        }
    } catch (error) {
        if (error !== 'cancel') {
            showError('删除失败')
        }
    }
}

// 查看详情
const handleViewDetails = (row: any) => {
    selectedLot.value = { ...row }
    detailsDialogVisible.value = true
}

// 查看车位
const handleViewSpaces = (row: any) => {
    // 模拟车位数据
    lotSpaces.value = [
        {
            spaceNo: `${row.lotName.charAt(0)}-001`,
            spaceTypeName: '普通车位',
            status: 1,
            statusName: '占用',
            licensePlate: '京A12345',
            ownerName: '张三',
            enterTime: '2024-01-15 10:30:00',
            duration: '2小时30分',
            fee: '12.50'
        },
        {
            spaceNo: `${row.lotName.charAt(0)}-002`,
            spaceTypeName: '普通车位',
            status: 0,
            statusName: '空闲',
            licensePlate: '',
            ownerName: '',
            enterTime: '',
            duration: '',
            fee: '0.00'
        },
        {
            spaceNo: `${row.lotName.charAt(0)}-003`,
            spaceTypeName: '充电车位',
            status: 1,
            statusName: '占用',
            licensePlate: '京C11111',
            ownerName: '王五',
            enterTime: '2024-01-15 11:00:00',
            duration: '1小时45分',
            fee: '8.75'
        }
    ]
    spacesDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    
    try {
        await formRef.value.validate()
        submitLoading.value = true
        
        // 模拟提交操作
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        if (form.id) {
            // 编辑模式
            const index = tableData.value.findIndex(item => item.id === form.id)
            if (index > -1) {
                Object.assign(tableData.value[index], {
                    ...form,
                    lotTypeName: getLotTypeName(form.lotType),
                    statusName: getStatusName(form.status)
                })
            }
            showSuccess('更新成功')
        } else {
            // 添加模式
            const newId = Math.max(...tableData.value.map(item => item.id)) + 1
            const newLot = {
                ...form,
                id: newId,
                lotTypeName: getLotTypeName(form.lotType),
                statusName: getStatusName(form.status),
                availableSpaces: form.totalSpaces,
                occupiedSpaces: 0,
                createTime: new Date().toLocaleString()
            }
            tableData.value.push(newLot)
            showSuccess('添加成功')
        }
        
        dialogVisible.value = false
    } catch (error) {
        showError('提交失败')
    } finally {
        submitLoading.value = false
    }
}

// 对话框关闭
const handleDialogClose = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
}

// 当前页改变
const handleCurrentChange = (current: number) => {
    pagination.current = current
}

// 获取停车场类型名称
const getLotTypeName = (type: number) => {
    switch (type) {
        case 1: return '地下停车场'
        case 2: return '地面停车场'
        case 3: return '立体车库'
        case 4: return '访客停车场'
        default: return '地下停车场'
    }
}

// 获取状态名称
const getStatusName = (status: number) => {
    switch (status) {
        case 1: return '正常'
        case 0: return '维护'
        default: return '正常'
    }
}

// 初始化
onMounted(() => {
    pagination.total = tableData.value.length
})
</script>

<style scoped>
.lot-container {
    padding: 20px;
}

.title-card {
    margin-bottom: 20px;
}

.page-header {
    text-align: center;
}

.page-header h2 {
    margin: 0 0 10px 0;
    color: #303133;
    font-size: 24px;
}

.page-description {
    margin: 0;
    color: #909399;
    font-size: 14px;
}

.search-card {
    margin-bottom: 20px;
}

.stats-row {
    margin-bottom: 20px;
}

.stats-card {
    height: 100px;
}

.stats-content {
    display: flex;
    align-items: center;
    height: 100%;
}

.stats-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    font-size: 24px;
    color: white;
}

.stats-icon.success {
    background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stats-icon.primary {
    background: linear-gradient(135deg, #409eff, #66b1ff);
}

.stats-icon.warning {
    background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stats-icon.info {
    background: linear-gradient(135deg, #909399, #c0c4cc);
}

.stats-info {
    flex: 1;
}

.stats-number {
    font-size: 28px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 5px;
}

.stats-label {
    font-size: 14px;
    color: #909399;
}

.operation-card {
    margin-bottom: 20px;
}

.table-card {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style> 